package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import com.atguigu.yygh.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * zz: wzh
 * time 2022 09 07 14 38
 **/
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //返送验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //冲redis中获取验证码,如果可以就返回ok
        //key为手机号,value为验证码
        String code = redisTemplate.opsForValue().get("phone");
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //获取不到就发送验证码
        code=RandomUtil.getSixBitRandom();
        System.out.println(code);
        boolean isSend=msmService.send(phone,code);
        //然后放到redis中,设置有效时间
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("短信发送失败");
        }
    }
}
